package com.minsf.rpc.protocol;

import com.minsf.rpc.serializer.Serializer;
import com.minsf.rpc.serializer.SerializerFactory;
import io.vertx.core.buffer.Buffer;

import java.io.IOException;

/**
 * @Description
 * @Author minify
 * @Date 2024/3/29 22:52
 * @Project sf-rpc
 */
public class ProtocolMessageEncoder {

    public static Buffer encode(ProtocolMessage<?> protocolMessage) throws IOException {
        Buffer buffer = Buffer.buffer();
        if (protocolMessage == null || protocolMessage.getHeader() == null) {
            return buffer;
        }
        ProtocolMessage.Header header = protocolMessage.getHeader();

        // 依次向缓冲区写入字节
        buffer.appendByte(header.getMagic());
        byte serializerByte = header.getSerializer();
        buffer.appendByte(serializerByte);
        buffer.appendByte(header.getType());
        buffer.appendByte(header.getStatus());
        buffer.appendByte(header.getVersion());
        buffer.appendLong(header.getRequestId());

        // 获取序列化器
        ProtocolMessageSerializerEnum serializerEnum = ProtocolMessageSerializerEnum.getEnumByKey(serializerByte);
        if (serializerEnum == null) {
            throw new RuntimeException("序列化协议不存在");
        }

        Serializer serializer = SerializerFactory.getSerializer(serializerEnum.getValue());
        // 写入消息体
        Object data = protocolMessage.getData();
        byte[] serialize = serializer.serialize(data);
        buffer.appendInt(serialize.length);
        buffer.appendBytes(serialize);

        return buffer;
    }
}
